<?php defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Department
 *
 *
 * @package		CodeIgniter
 * @subpackage	Rest Server
 * @category	Controller
 * @author		Tuan NT
 * @link		http://bungtay.com/hrm3/
*/

// This can be removed if you use __autoload() in config.php OR use Modular Extensions
require APPPATH.'/libraries/REST_Controller.php';

class Department extends REST_Controller{
    
    function __construct(){
        parent::__construct();
        //$this->load->model('user','',TRUE);
        $this->load->model(array('department_model','user_model','staff_model'));

    }
    

    /**
     * 
     * Get one Department by Id
     * @author TuanNt
     * @link http://localhost/hrm/api/department/departmentById/id/$id/format/json
     * @param Integer $id
     * @return Json one Department
     * 
     **/
    function byid_get(){
        $token = $this->get('token');
        $token_secret = $this->get('token_secret');

        $this->oauth($token);

        $id = $this->get('id');
        if(!$id){
        	$this->response(NULL, 400);
        }

        $oneDepartment = $this->department_model->getSingleDepartment(array('iddepartment'=>$id));
        
        if(!empty($oneDepartment)){
           $this->response(array('result'=>$oneDepartment),200); 
        }else{
            $this->response(array('error' => 'Department could not be found'), 404);
        }
    }

    public function auth_post(){
        $params = json_decode(file_get_contents('php://input'), true);

        $username = $params['username'];

        $password = $params['password'];

        $result = $this->user_model->login($username, $password);
        
        if($result){
            $sess_array = array();
            foreach($result as $row){
                
                $token = md5(uniqid(mt_rand(), true));
                if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
                    $ip = $_SERVER['HTTP_CLIENT_IP'];
                } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
                } else {
                    $ip = $_SERVER['REMOTE_ADDR'];
                }

                $dietime=time()+10800;

                $data = array('key'=>$token,'level'=>1,'limit'=>1,'username'=>$username,'ipaddress'=>$ip,'date_created'=>$dietime); 
                $this->user_model->addKey($data);   
            }

            $this->response(array("token"=>$token), 200); 
        }else{
            $this->response(array('result'=>'false'),200); 
        }                     
    }
    
    /**
     * 
     * Get all List Departments
     * @author TuanNt
     * @link http://localhost/hrm/api/department/departments/format/json
     * @return Json List Department
     * 
     **/
    function list_get(){
        $token = $this->get('token');
        $token_secret = $this->get('token_secret');

        $this->oauth($token);

        $limit = $this->get('limit');
        $offset = $this->get('offset');

        $departments = $this->department_model->getListDepartment($limit,$offset);
        
        if($departments){
            $this->response(array('result'=>$departments),200);
        }else{
            $this->response(array('error' => 'No have any department'), 404);
        }
    }


    function listgroup_get(){
        $token = $this->get('token');
        $token_secret = $this->get('token_secret');

        $this->oauth($token);

        $limit = $this->get('limit');
        $offset = $this->get('offset');

        $departments = $this->department_model->getListDepartment($limit,$offset);
        $staffs = $this->staff_model->getListStaff();
        $arr = array();
        foreach ($departments as $keyd => $d) {
            # code...
            $did = $d['iddepartment'];
            $dname = $d['name'];
            $kk = array();
            foreach ($staffs as $keys => $s) {
                # code...
                
                if($did==$s['iddepartment']){
                    $kk[]=$s;
                }
            }
            $arr[$dname] = $kk;
        }
        if($departments){
            $this->response(array('result'=>$arr),200);
        }else{
            $this->response(array('error' => 'No have any department'), 404);
        }
    }
    
    /**
     * 
     * Update one Staff
     * @author TuanNt
     * @link http://localhost/hrm/api/department/departmentEdit/id/
     * @return Json
     * 
     **/
    function add_post(){
        $params = json_decode(file_get_contents('php://input'), TRUE);

            $token = $this->get('token');

            $this->oauth($token);

            $param['name'] = $params['name'];

            $param['description'] = $params['description'];

            $param["dateupdated"]   = time();

            $param["datecreated"]   = time();
            
            if($this->department_model->addDepartment($param)){
                $this->response(array('result'=>'true'), 200);    
            }else{
                $this->response(array('result'=>'false'), 200);    
            }
    }

    function update_post(){
        $params = json_decode(file_get_contents('php://input'), TRUE);

            $token = $this->get('token');

            

            $this->oauth($token);
                    
            $param['name'] = $params['name'];

            $param['description'] = $params['description'];

            $param["dateupdated"]   = time();

            $condition = array('iddepartment'=>$params['id']);

            if($this->department_model->updateDepartment($param,$condition)){
                $this->response(array('result'=>'true'), 200);    
            }else{
                $this->response(array('result'=>'false'), 200);    
            }
    }

    function delete_post(){
        $params = json_decode(file_get_contents('php://input'), TRUE);
            
            $token = $this->get('token');

            

            $this->oauth($token);

            if($this->department_model->deleteDepartment(array('iddepartment'=>$params['id']))){
                $this->response(array('result'=>'true'), 200);    
            }else{
                $this->response(array('result'=>'false'), 200);    
            }
    }

    function oauth($token,$token_secret=null){
        //token=ab3cd9j4ks73hf7g&token_secret=xyz4992k83j47x0b
        $oauth = $this->user_model->auth_token($token);
        if($oauth){
            if(time()<$oauth['date_created']){
                    $cnttime = time()+10800;
                        
                    $data = array('date_created'=>$cnttime);
                    $cont = array('id' => $oauth['id']);
                    $xs = $this->user_model->updateKey($data,$cont);
                    //$this->response($xs, 200);
            }else{
                $this->response(array('error' => 'Wrong token'), 401);
            }
        }else{
            $this->response(array('error' => 'Wrong token'), 401);
        }
    }
        
}

?>